package com.seele.tigerwallet.ui.views;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.model.AssetsModel;
import com.seele.tigerwallet.model.WebModel;
import com.seele.tigerwallet.ui.activtiy.WebViewActivtiy;
import com.seele.tigerwallet.ui.adapter.AssetsSreachAdapter;
import com.seele.tigerwallet.ui.callback.BaseListener;
import com.seele.tigerwallet.ui.callback.OnSelectListener;
import com.seele.tigerwallet.ui.utils.DividerItemDecoration;
import com.seele.tigerwallet.ui.utils.GsonUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AssetsSearchRecyclerView extends RecyclerView implements BaseQuickAdapter.RequestLoadMoreListener {

    private AssetsSreachAdapter mSreachAdapter;
    private List<AssetsModel> mBundleList;//传值
    private int num = 30;
    private List<Integer> list = new ArrayList<>();
    private OnSelectListener onSelectListener;
    private String mKeyword;

    private Map<Integer, AssetsModel> modelMap = new ConcurrentHashMap<>();

    private Context mContext;
    private boolean isEmpty;
    private View mErrorView;
    private View mEptyView;


    public void setListener(BaseListener listener) {
        if (listener instanceof OnSelectListener) {
            this.onSelectListener = (OnSelectListener) listener;
        }
    }


    public AssetsSearchRecyclerView(Context context) {
        this(context, null);
    }


    public AssetsSearchRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AssetsSearchRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        initView(context);
    }


    private TextView mSubmitToken;

    /**
     * @param context
     */
    private void initView(Context context) {

        mErrorView = View.inflate(context, R.layout.search_error_view, null);
        mSubmitToken = mErrorView.findViewById(R.id.submit_token);
        mSubmitToken.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                WebModel webModel = new WebModel();
                webModel.title =getResources().getString(R.string.cause);
                webModel.isDisplay = false;
                webModel.isHtmlTitle = false;
                webModel.url = APIModule.getTokeninfoURL();
                Bundle bundle = new Bundle();
                bundle.putSerializable(WebViewActivtiy.class.getSimpleName(), webModel);
                Intent intent=new Intent(mContext,WebViewActivtiy.class);
                intent.putExtras(bundle);
                mContext.startActivity(intent);

            }
        });
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mErrorView.setLayoutParams(layoutParams);

        mEptyView = View.inflate(mContext, R.layout.empty_view, null);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mEptyView.setLayoutParams(params);

        if (null == context) {
            return;
        }
        setLayoutManager(new LinearLayoutManager(context));
        addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.HORIZONTAL, (int) getResources().getDimension(R.dimen.dp_1), getResources().getColor(R.color.color_F9F9F9))); //设置item的分割线
        if (null == mSreachAdapter) {
            mSreachAdapter = new AssetsSreachAdapter(R.layout.item_add_assets);
        }
//        mSreachAdapter.setOnLoadMoreListener(this, this);
//        mSreachAdapter.setEnableLoadMore(true);
        setAdapter(mSreachAdapter);

        mSreachAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                AssetsModel item = null;
                if (null != mSreachAdapter) {
                    item = mSreachAdapter.getData().get(position);
                }
                switch (view.getId()) {
                    case R.id.check_ll:
                        handlerSelect(item);
                        break;
                }
            }
        });
    }

    public void addAssetsModel(AssetsModel assetsModel) {
        if (null != assetsModel) {
            if (!modelMap.containsKey(assetsModel.id)) {
                modelMap.put(assetsModel.id, assetsModel);
            }
        }
    }

    public void addAssetsModel(List<AssetsModel> assetsModel) {
        for (AssetsModel model : assetsModel) {
            if (null != assetsModel) {
                if (!modelMap.containsKey(model.id)) {
                    modelMap.put(model.id, model);
                }
            }
        }

    }


    /**
     * 处理选择的资产
     *
     * @param item
     */
    private void handlerSelect(AssetsModel item) {
        if (null == item) {
            return;
        }
        if (null == mBundleList) {
            mBundleList = new ArrayList<>();
        }
        boolean isOpen = item.isOpen;
        if (isOpen) {
            item.isOpen = false;
        } else {
            item.isOpen = true;
        }
        mSreachAdapter.notifyDataSetChanged();
        clear();
        for (AssetsModel assetsModel : mBundleList) {
            list.add(assetsModel.id);
        }
        if (item.isOpen) {
            if (!list.contains(item.id)) {
                mBundleList.add(item);
            }
        } else {
            if (list.contains(item.id)) {
                for (int i = mBundleList.size() - 1; i >= 0; i--) {
                    if (mBundleList.get(i).id == item.id) {
                        mBundleList.remove(i);
                    }
                }
            }
        }

        if (null != onSelectListener) {
            if (null != mBundleList) {
                onSelectListener.onSelect(mBundleList);
            }
        }
    }

    /**
     * 请求数据
     *
     * @param keyword
     * @param id
     * @param isRefresh
     */
    private void initData(String keyword, int id, final boolean isRefresh) {
        APIModule
                .getApi()
                .searchBalance(keyword, id, num)
                .enqueue(new APIListCallBack<AssetsModel>() {
                    @Override
                    protected void onResponse(List<AssetsModel> response) {
                        int size = response == null ? 0 : response.size();
                        //表示值为空
                        if (isEmpty) {
                            //设置空的View
                            mSreachAdapter.setNewData(null);
                            mSreachAdapter.setEmptyView(mEptyView);
                        } else {
                            if (isRefresh && size == 0) {
                                //设置搜索错误的View
                                mSreachAdapter.setNewData(null);
                                mSreachAdapter.setEmptyView(mErrorView);
                            } else {
                                handleData(response, isRefresh);
                            }

                        }
                    }

                    @Override
                    protected void onResponseError(APIException e) {

                        //设置搜索错误的View
                        mSreachAdapter.setNewData(null);
                        mSreachAdapter.setEmptyView(mErrorView);
                        if (!isRefresh) {
                            mSreachAdapter.loadMoreFail();
                        }

                        if (!isRefresh) {
                            mSreachAdapter.loadMoreFail();
                        }


                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        //设置搜索错误的View
                        mSreachAdapter.setNewData(null);
                        mSreachAdapter.setEmptyView(mErrorView);
                        if (!isRefresh) {
                            mSreachAdapter.loadMoreFail();
                        }
                    }


                });
    }

    /**
     * 数据处理
     *
     * @param response
     * @param isRefresh
     */
    private void handleData(List<AssetsModel> response, boolean isRefresh) {
        int size = response == null ? 0 : response.size();
        if (size > 0) {
            clear();
            if (null == mBundleList) {
                mBundleList = new ArrayList<>();
            }
//            modelMap.clear();

            for (AssetsModel assetsModel : response) {
                assetsModel.candisable = 1;
                if (modelMap.containsKey(assetsModel.id)) {
                    AssetsModel assetsModel2 = modelMap.get(assetsModel.id);
                    assetsModel.candisable = assetsModel2.candisable;
                    assetsModel.isOpen = assetsModel2.isOpen;
                }
            }


            if (isRefresh) {
                setAdapter(mSreachAdapter);
                mSreachAdapter.setNewData(response);
                mSreachAdapter.notifyDataSetChanged();
            } else {
                mSreachAdapter.addData(response);
                mSreachAdapter.loadMoreComplete();
            }
        } else {
            if (isRefresh) {
                setAdapter(mSreachAdapter);
                mSreachAdapter.setNewData(response);
            } else {
                mSreachAdapter.loadMoreEnd(isRefresh);
            }
        }
    }


    private void clear() {
        if (list.size() > 0) {
            list.clear();
        }

    }

    /**
     * 设置
     */
    public void setBundleList(List<AssetsModel> bundleList, String keyword) {


        this.mBundleList = bundleList;

        if (null == bundleList) {
            bundleList = new ArrayList<>();
        }
        if (null != bundleList && bundleList.size() > 0) {
            for (AssetsModel assetsModel : bundleList) {
                addAssetsModel(assetsModel);
            }
        }


        this.mKeyword = keyword;
        if (!TextUtils.isEmpty(mKeyword)){
            mKeyword = mKeyword.toString().trim();
        }

        if (TextUtils.isEmpty(mKeyword)) {
            mSreachAdapter.setNewData(null);
            mSreachAdapter.setEmptyView(mErrorView);
            isEmpty = true;
        } else {
            isEmpty = false;

            initData(mKeyword, 0, true);
        }
    }


    @Override
    public void onLoadMoreRequested() {
        if (null != mSreachAdapter) {
            List<AssetsModel> assetsModels = mSreachAdapter.getData();
            int size = assetsModels == null ? 0 : assetsModels.size();
            if (size > 0) {
                int id = assetsModels.get(size - 1).id + 1;
                initData(mKeyword, id, false);
            }
        }


    }

    public void setNormal() {
        mSreachAdapter.setNewData(null);
        mSreachAdapter.notifyDataSetChanged();
    }
}
